/**
 * 
 */
package com.ht.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StringUtil {
	
	private static final Logger log = LoggerFactory.getLogger(StringUtil.class);
	
	private static final String[] RANDOM_STR = { "1", "2", "3", "4", "5", "6", "7", "8",
		"9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
		"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
		"x", "y", "z" };
	
	public static boolean isEmpty(String str){
		return null == str? true:str.trim().length() == 0;
	}
	
	public static boolean isEmpty(Map<?,?> map){
		return null == map? true:map.size() == 0;
	}
	
	public static boolean isEmpty(Collection<?> collection){
		return null == collection?true:collection.size() == 0;
	}
	
	public static boolean isEquals(String str1, String str2){
		if(isEmpty(str1) && isEmpty(str2)){
			return true;
		}
		if(null != str1){
			return str1.equals(str2);
		}
		if(null != str2){
			return str2.equals(str1);
		}
		return false;
	}
	
	/**
	 * 生成数据库主键ID
	 * 采用日期(17位)加随机数(8位)的方式
	 */
	public static String createId(){
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		StringBuffer sb = new StringBuffer();
		sb.append(df.format(Calendar.getInstance().getTime()));
		for(int j = 0 ; j < 8; j++){
			sb.append(RANDOM_STR[new Random().nextInt(35)]);
		}
		return(sb.toString());
	}

	/**
	 * Convert Date to String using format yyyy-MM-dd
	 * @param date
	 * @return
	 */
	public static String date2String(Date date){
		if(null != date){
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			return df.format(date);
		}
		return "";
	}
	
	public static Date string2Date(String dateStr){
		if(!StringUtil.isEmpty(dateStr)){
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			try {
				return df.parse(dateStr);
			} catch (ParseException e) {
				log.error("日期转换失败！{}",dateStr,e);
			}
		}
		return null;
	}
	
	public static String getHeader(String str){
		if(isEmpty(str)){
			return str;
		}
		int index = str.lastIndexOf(".");
		if(index != -1){
			return str.substring(0,index);
		}
		return str;
	}
	
	public static String dateTime2String(Date date){
		if(null != date){
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			return df.format(date);
		}
		return "";
	}
	
	public static Date string2DateTime(String dateStr){
		if(!StringUtil.isEmpty(dateStr)){
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			try {
				return df.parse(dateStr);
			} catch (ParseException e) {
				log.error("日期转换失败！{}",dateStr,e);
			}
		}
		return null;
	}
}
